import { Pressable, StyleSheet, Text, View, Image, PermissionsAndroid } from 'react-native';
import React, { useState, useEffect, useRef, useCallback } from 'react';
import { FocusAwareStatusBar } from '~/components';
import {
    ChannelProfileType,
    ClientRoleType,
    createAgoraRtcEngine,
    ErrorCodeType,
    RtcConnection,
    RtcStats,
    RtcSurfaceView,
    UserOfflineReasonType,
    VideoViewSetupMode,
    RenderModeType,
    RemoteVideoState,
    RemoteVideoStateReason,
    StreamSubscribeState,
    VideoDenoiserOptions,
    VideoDenoiserLevel,
    MediaSourceType,
    VideoDenoiserMode,
} from 'react-native-agora';
import { useNavigation, useRoute } from '@react-navigation/native';
import LinearGradient from 'react-native-linear-gradient';
import { useTranslation } from 'react-i18next';
import { isIos, px2dp, scale, width } from '~/utils/px2dp';
import { agoraId } from '!/app.json';
import { getRtcTokenApi } from '~/api/deviceApi';
import { observer } from '~/store';
import { useTimeout, useTimer } from '~/common';
import { exitChannel, joinCallChannel } from '~/utils/socketMessenger';

export default observer(() => {
    const router: any = useRoute();
    const navigation: any = useNavigation();
    const { t } = useTranslation();

    const {
        device_sn = '',
        user_name = '',
        fo_type = '',
        to_uid = '',
        // 设备来电参数
        to_token,
        fo_uid,
        channel_id,
        type,
    } = router.params || {};
    const [sound, setSound] = useState(false); // 默认不免提
    const [isTimeout, startTimer, resetTimer] = useTimeout(60); // 获取超时相关
    const { time, startRunTimer, stopRunTimer, resetRunTimer } = useTimer();
    const engine = useRef<any>(createAgoraRtcEngine());
    const [setupMode] = useState(VideoViewSetupMode.VideoViewSetupReplace);
    const [successVideo, setSuccessVideo] = useState(false); // 是否有视频
    const [remoteUsers, setRemoteUsers] = useState<number[]>([]);
    // 挂断电话
    const hangUp = () => {
        leaveChannel();
        exitChannel(device_sn);
        navigation.goBack();
    };

    // 主动app=>硬件
    const getRtcToken = () => {
        let obj = {
            device_sn: device_sn,
            fo_type,
            to_uid,
        };
        getRtcTokenApi(obj).then((res) => {
            if (res.data.busy_line == 1) {
                Toast.show({ content: t('callDevice.t1'), layout: 'top' });
                navigation.goBack();
                return;
            }
            const { channel_name, fo_token, fo_uid } = res.data;
            joinChannel(fo_token, channel_name, parseInt(fo_uid));
            startTimer(); // 倒计时开始
        });
    };

    // 硬件=>app
    const inComingCall = () => {
        joinChannel(to_token, channel_id, parseInt(fo_uid));
    };

    // 离开房间
    const leaveChannel = () => {
        engine.current.leaveChannel();
    };
    // 加入房间
    const joinChannel = (token, channelId, uid) => {
        if (uid < 0) {
            return;
        }
        if (!channelId) {
            return;
        }
        engine.current.joinChannel(token, channelId, uid, {
            clientRoleType: ClientRoleType.ClientRoleBroadcaster,
        });
        joinCallChannel(device_sn, { channel_id });
    };
    const initRtcEngine = useCallback(async () => {
        engine.current.initialize({
            appId: agoraId,
            channelProfile: ChannelProfileType.ChannelProfileLiveBroadcasting,
        });
        if (!isIos()) {
            await PermissionsAndroid.requestMultiple(['android.permission.RECORD_AUDIO', 'android.permission.CAMERA']);
        }
        engine.current.setParameters(`{\"che.audio.custom_payload_type\":9}`); // 设置G722格式
        engine.current.enableVideo();
        const VideoOptions = new VideoDenoiserOptions();
        VideoOptions.level = VideoDenoiserLevel.VideoDenoiserLevelFast;
        VideoOptions.mode = VideoDenoiserMode.VideoDenoiserAuto;
        engine.current.setVideoDenoiserOptions(true, VideoOptions, MediaSourceType.PrimaryCameraSource);
        engine.current.startPreview();
    }, [agoraId]);

    useEffect(() => {
        if (type == 'inComing') {
            setTimeout(() => {
                inComingCall();
            }, 1000);
        } else {
            getRtcToken();
        }
    }, []);

    useEffect(() => {
        initRtcEngine()
            .then((res) => {
                engine.current.addListener('onError', (err: ErrorCodeType, msg: string) => {
                    console.info('onError', 'err', err, 'msg', msg);
                });
                engine.current.addListener('onJoinChannelSuccess', (connection: RtcConnection, elapsed: number) => {
                    console.info('加入当前房间>>>>>', 'connection', connection, 'elapsed', elapsed);

                    engine.current.setEnableSpeakerphone(false);
                    setSound(false);
                });
                engine.current.addListener('onLeaveChannel', (connection: RtcConnection, stats: RtcStats) => {
                    console.info('离开当前房间>>>>>', 'connection', connection, 'stats', stats);
                    setRemoteUsers([]);
                });

                engine.current.addListener(
                    'onUserJoined',
                    (connection: RtcConnection, remoteUid: number, elapsed: number) => {
                        resetTimer(); // 如果有这个回调，那么就重置这个时间段；
                        startRunTimer(); // 开始计算通话时长
                        setRemoteUsers((r) => {
                            if (r === undefined) return [];
                            return [...r, remoteUid];
                        });
                    },
                );

                engine.current.addListener(
                    'onUserOffline',
                    (connection: RtcConnection, remoteUid: number, reason: UserOfflineReasonType) => {
                        console.info(
                            '检测用户离开的回调',
                            'connection',
                            connection,
                            'remoteUid',
                            remoteUid,
                            'reason',
                            reason,
                        );
                        setRemoteUsers((r) => {
                            if (r === undefined) return [];
                            return r.filter((value) => value !== remoteUid);
                        });
                        Toast.show({ content: t('callDevice.t2'), layout: 'top' });
                        stopRunTimer();
                        setTimeout(() => {
                            navigation.goBack();
                        }, 1000);
                    },
                );
                engine.current.addListener(
                    'onFirstRemoteVideoDecoded',
                    (connection: RtcConnection, remoteUid: number, width: number, height: number, elapsed: number) => {
                        console.info('已接收到远端视频并完成解码回调', connection, 'remoteUid', remoteUid);
                    },
                );
                engine.current.addListener(
                    'onFirstRemoteVideoFrame',
                    (connection: RtcConnection, remoteUid: number, width: number, height: number, elapsed: number) => {
                        console.info('渲染器已接收首帧远端视频回调。', connection, 'remoteUid', remoteUid);
                    },
                );
                engine.current.addListener(
                    'onVideoSubscribeStateChanged',
                    (
                        channel: string,
                        uid: number,
                        oldState: StreamSubscribeState,
                        newState: StreamSubscribeState,
                        elapseSinceLastState: number,
                    ) => {
                        console.info('视频订阅状态改变时触发', oldState, newState, elapseSinceLastState);
                    },
                );
                engine.current.addListener(
                    'onRemoteVideoStateChanged',
                    (
                        connection: RtcConnection,
                        remoteUid: number,
                        state: RemoteVideoState,
                        reason: RemoteVideoStateReason,
                        elapsed: number,
                    ) => {
                        if (state == 2 || state == 1) {
                            setSuccessVideo(true);
                            return;
                        }
                        setSuccessVideo(false);
                        if (reason == 3) {
                            return;
                        }
                        Toast.show({ content: t('callDevice.t3'), layout: 'top' });
                    },
                );
            })
            .catch((err) => {
                console.log('声网错误', err);
            });
        const engineCopy = engine.current;
        return () => {
            engineCopy.release();
        };
    }, [initRtcEngine]);

    // 检测用户未接听
    useEffect(() => {
        if (isTimeout) {
            hangUp();
            Toast.show({ content: t('callDevice.t4'), layout: 'top' });
        }
    }, [isTimeout]);

    // const shakeAnim = useRef(new Animated.Value(0)).current;
    // const fadeAnim = useRef(new Animated.Value(1)).current;
    // const [visible, setVisible] = useState(true);
    // useEffect(() => {
    //     // 抖动动画
    //     Animated.sequence([
    //         // 向上移动
    //         Animated.timing(shakeAnim, {
    //             toValue: -8,
    //             duration: 300,
    //             useNativeDriver: true,
    //         }),
    //         // 向下抖动
    //         Animated.timing(shakeAnim, {
    //             toValue: 5,
    //             duration: 150,
    //             useNativeDriver: true,
    //         }),
    //         // 轻微回弹
    //         Animated.timing(shakeAnim, {
    //             toValue: -2,
    //             duration: 100,
    //             useNativeDriver: true,
    //         }),
    //         // 恢复原位
    //         Animated.timing(shakeAnim, {
    //             toValue: 0,
    //             duration: 100,
    //             useNativeDriver: true,
    //         }),
    //     ]).start();

    //     // 5秒后淡出并隐藏
    //     const timer = setTimeout(() => {
    //         Animated.timing(fadeAnim, {
    //             toValue: 0,
    //             duration: 500,
    //             useNativeDriver: true,
    //         }).start(() => setVisible(false));
    //     }, 5000);

    //     return () => clearTimeout(timer);
    // }, []);

    const isEmpity = () => {
        return (
            <LinearGradient colors={['#385149', '#595E53', '#38514A']} style={styles.linearGradient}>
                <FocusAwareStatusBar translucent={true} backgroundColor="#38514A" barStyle="light-content" />
                <View style={styles.container}>
                    <View style={styles.nameContent}>
                        <Text style={styles.callStatus}>
                            {remoteUsers.length > 0 ? t('callDevice.t5') : t('callDevice.t6')}
                        </Text>
                        <Text style={styles.userName}>{user_name || t('callDevice.t7')}</Text>
                    </View>
                    <>
                        {/* 成功加载出对方画面 */}
                        {remoteUsers !== undefined && remoteUsers.length > 0 && successVideo ? (
                            <>
                                {remoteUsers.map((value, index) => {
                                    return (
                                        <View key={index}>
                                            <RtcSurfaceView
                                                style={styles.videoSmall}
                                                zOrderMediaOverlay={true}
                                                canvas={{
                                                    view: null,
                                                    uid: value,
                                                    renderMode: RenderModeType.RenderModeHidden,
                                                    setupMode,
                                                }}
                                            />
                                        </View>
                                    );
                                })}
                            </>
                        ) : undefined}
                    </>
                    {/* <VolumeControl
                        position="right"
                        barHeight={px2dp(400)}
                        barWidth={px2dp(140)}
                        barColor="#eeeeee"
                        onVolumeEnd={onVolumeEnd}
                        initialVolume={volume}
                    />
                    {visible && (
                        <Animated.Text
                            style={[
                                styles.volum,
                                {
                                    transform: [{ translateX: shakeAnim }],
                                },
                            ]}>
                            上下滑动调节设备音量
                        </Animated.Text>
                    )} */}

                    <View style={styles.bottom}>
                        {remoteUsers.length > 0 && <Text style={styles.time_color}>{time}</Text>}
                        <View style={styles.row}>
                            <Pressable
                                onPress={() => {
                                    engine.current.setEnableSpeakerphone(!sound);
                                    setSound(!sound);
                                }}>
                                <View style={[styles.border, sound && { backgroundColor: '#fff' }]}>
                                    <Image
                                        source={require('~/assets/call/hands_free.png')}
                                        style={[styles.free, sound && { tintColor: '#000' }]}
                                    />
                                </View>
                                <Text style={[styles.t1]}>{t('callDevice.t8')}</Text>
                            </Pressable>
                            <Pressable onPress={hangUp}>
                                <Image source={require('~/assets/call/hangup.png')} style={styles.icons} />
                                <Text style={styles.t1}>{t('callDevice.t9')}</Text>
                            </Pressable>
                        </View>
                    </View>
                </View>
            </LinearGradient>
        );
    };
    return <View style={styles.linearGradient}>{isEmpity()}</View>;
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'space-around',
    },
    videoSmall: {
        height: 360,
    },
    linearGradient: {
        flex: 1,
    },
    container: {
        flex: 1,
        marginTop: isIos() ? '16%' : '12%',
    },
    callStatus: {
        color: '#ADB0B1',
        marginBottom: px2dp(10),
        fontSize: scale(40),
        fontWeight: 'bold',
    },
    nameContent: {
        alignItems: 'center',
        marginTop: '10%',
        marginBottom: '10%',
    },
    userName: {
        color: '#fff',
        fontSize: scale(40),
        fontWeight: 'bold',
    },
    bottom: {
        position: 'absolute',
        width: width,
        bottom: '10%',
    },
    time_color: {
        color: '#fff',
        textAlign: 'center',
        marginBottom: '16%',
        fontSize: scale(40),
        letterSpacing: 1,
    },
    icons: {
        width: px2dp(120),
        height: px2dp(120),
    },
    t1: {
        color: '#fff',
        textAlign: 'center',
        marginTop: px2dp(10),
    },
    border: {
        justifyContent: 'center',
        alignItems: 'center',
        backgroundColor: '#4E6C62',
        width: px2dp(120),
        height: px2dp(120),
        borderRadius: px2dp(60),
    },
    free: {
        width: px2dp(50),
        height: px2dp(50),
    },
    volum: {
        // width: px2dp(140),
        color: '#fff',
        fontSize: scale(24),
    },
});
